package com.example.library_common.album.ui

import android.content.DialogInterface
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.View
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.transition.Transition
import com.example.su_shi_tan_bas_lib.album.view.editor_img.view.AlbumEditorImg
import com.example.su_shi_tan_bas_lib.R
import com.example.su_shi_tan_bas_lib.album.bean.AlbumFile
import com.example.su_shi_tan_bas_lib.album.view.editor_img.IMGTextEditDialog
import com.example.su_shi_tan_bas_lib.album.view.editor_img.core.IMGMode
import com.example.su_shi_tan_bas_lib.album.view.editor_img.core.IMGText
import com.example.su_shi_tan_bas_lib.base.BaseDataBindingFragment
import com.example.su_shi_tan_bas_lib.databinding.FragmentEditorImgLayoutBinding
import com.example.su_shi_tan_bas_lib.glidmodule.GlideApp
import java.io.File
import java.io.FileOutputStream


class EditorImgFragment : BaseDataBindingFragment<FragmentEditorImgLayoutBinding>(),
    View.OnClickListener,

    DialogInterface.OnShowListener,
    DialogInterface.OnDismissListener, IMGTextEditDialog.Callback {

    companion object {

        const val OP_HIDE = -1

        const val OP_NORMAL = 0

        const val OP_CLIP = 1

        const val OP_SUB_DOODLE = 0

        const val OP_SUB_MOSAIC = 1

        fun newInstance(mAlbumFile: AlbumFile) = EditorImgFragment().apply {
            val bundle = Bundle()
            bundle.putSerializable("mAlbumFile", mAlbumFile)
            arguments = bundle
        }
    }

    private lateinit var mAlbumFile: AlbumFile

    private var mTextDialog: IMGTextEditDialog? = null

    private var resultListener: EditorResultListener? = null

    fun setResultListener(resultListener: EditorResultListener) {
        this.resultListener = resultListener
    }

    override fun layoutId() = R.layout.fragment_editor_img_layout


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = true
        mAlbumFile = arguments?.getSerializable("mAlbumFile") as AlbumFile
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinder.onViewClick = this
        viewBinder.editorImgOpt.cgColors.setOnCheckedChangeListener { _, _ ->

            if (viewBinder.mEditorImg.getMode() === IMGMode.MOSAIC) {
                onModeClick(IMGMode.DOODLE)
            }

            onColorChanged(viewBinder.editorImgOpt.cgColors.checkColor)
        }

        updateModeUI()

        GlideApp.with(_mActivity)
            .asBitmap()
            .load(mAlbumFile.path)
            .into(object : CustomViewTarget<AlbumEditorImg, Bitmap>(viewBinder.mEditorImg) {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    viewBinder.mEditorImg.setBitmap(resource)
                }

                override fun onLoadFailed(errorDrawable: Drawable?) {
                }

                override fun onResourceCleared(placeholder: Drawable?) {

                }
            })
    }

    private fun onColorChanged(checkColor: Int) {
        viewBinder.mEditorImg.setPenColor(checkColor)
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.backUpBtn -> pop()
            R.id.mosaic -> {
                onModeClick(IMGMode.MOSAIC)
            }
            R.id.addBrush -> {
                onModeClick(IMGMode.DOODLE)
            }
            R.id.addImg -> {

            }
            R.id.btn_undo -> {
                onUndoClick()
            }
            R.id.charter -> {
                onTextModeClick()
            }
            R.id.cropper -> {
                onModeClick(IMGMode.CLIP)
            }
            R.id.ib_clip_rotate -> {
                onRotateClipClick()
            }
            R.id.ib_clip_cancel -> {
                onCancelClipClick()
            }
            R.id.ib_clip_done -> {
                onDoneClipClick()
            }
            R.id.tv_clip_reset -> {
                onResetClipClick()
            }
            R.id.submit_area -> {
                onDoneClick()
            }
        }
    }

    private fun onDoneClick() {
        val temp = saveImgPath()
        val saveBitmap = viewBinder.mEditorImg.saveBitmap()
        var os: FileOutputStream? = null
        try {
            os = FileOutputStream(temp)
            saveBitmap?.compress(Bitmap.CompressFormat.JPEG, 90, os)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                os?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        mAlbumFile.editorPath = temp

        resultListener?.onResult(mAlbumFile)

        pop()


    }

    private fun saveImgPath() = mAlbumFile.path.apply {

        val lastIndexOfPoint = lastIndexOf(".")

        val rootPath = substring(0, lastIndexOfPoint)

        val rootFile = File(rootPath)
        if (!rootFile.exists()) {
            rootFile.mkdirs()
        }

        val file = File(rootFile, "cropper-${System.currentTimeMillis()}.jpeg")
        if (!file.exists()) {
            file.createNewFile()
        }
        Log.d("saveImgPath", "file.path: ${file.path}")
        return file.path
    }

    private fun onResetClipClick() {
        viewBinder.mEditorImg.resetClip()
    }

    private fun onDoneClipClick() {
        viewBinder.backUpBtn.visibility = View.VISIBLE
        viewBinder.mEditorImg.doClip()
        val mode = viewBinder.mEditorImg.getMode()
        setOpDisplay(if (mode === IMGMode.CLIP) OP_CLIP else OP_NORMAL)
    }

    private fun onCancelClipClick() {
        viewBinder.backUpBtn.visibility = View.VISIBLE
        viewBinder.mEditorImg.cancelClip()
        val mode = viewBinder.mEditorImg.getMode()
        setOpDisplay(if (mode === IMGMode.CLIP) OP_CLIP else OP_NORMAL)
    }

    private fun onRotateClipClick() {
        viewBinder.mEditorImg.doRotate()
    }

    private fun onUndoClick() {
        val mode: IMGMode? = viewBinder.mEditorImg.getMode()
        if (mode === IMGMode.DOODLE) {
            viewBinder.mEditorImg.undoDoodle()
        } else if (mode === IMGMode.MOSAIC) {
            viewBinder.mEditorImg.undoMosaic()
        }
    }

    private fun onTextModeClick() {

        if (mTextDialog == null) {
            mTextDialog = IMGTextEditDialog(_mActivity, this)
            mTextDialog?.setOnShowListener(this)
            mTextDialog?.setOnDismissListener(this)
        }
        mTextDialog?.show()
    }


    private fun getCheckMode(mode: IMGMode): IMGMode {

        val tempMode: IMGMode = mode

        return when (viewBinder.mEditorImg.getMode()) {
            IMGMode.NONE -> tempMode
            tempMode -> IMGMode.NONE
            else -> tempMode
        }
    }

    private fun onModeClick(mode: IMGMode) {
        val checkMode = getCheckMode(mode)
        viewBinder.mEditorImg.setMode(checkMode)

        updateModeUI()


    }

    private fun updateModeUI() {
        viewBinder.backUpBtn.visibility = View.VISIBLE
        viewBinder.editorImgOpt.addBrush.isSelected = false
        when (viewBinder.mEditorImg.getMode()) {
            IMGMode.DOODLE -> {
                viewBinder.editorImgOpt.addBrush.isSelected = true
                setOpSubDisplay(OP_SUB_DOODLE)
            }
            IMGMode.MOSAIC -> {

                viewBinder.editorImgOpt.addBrush.isSelected = true
                setOpSubDisplay(OP_SUB_DOODLE)
            }
            IMGMode.NONE -> {
                viewBinder.editorImgOpt.cgColors.clearCheck()
                setOpSubDisplay(OP_HIDE)
            }
            IMGMode.CLIP -> {
                setOpDisplay(OP_CLIP)
                viewBinder.backUpBtn.visibility = View.GONE
            }
            else -> {
                viewBinder.editorImgOpt.cgColors.clearCheck()
                setOpSubDisplay(OP_HIDE)
            }
        }
    }

    private fun setOpDisplay(op: Int) {
        if (op >= 0) {
            viewBinder.vsOp.displayedChild = op
        }
    }

    private fun setOpSubDisplay(opSub: Int) {
        if (opSub < 0) {
            viewBinder.editorImgOpt.layoutOpSub.visibility = View.GONE

        } else {
            viewBinder.editorImgOpt.layoutOpSub.visibility = View.VISIBLE

            viewBinder.editorImgOpt.vsOpSub.displayedChild = opSub
        }
    }


    override fun onShow(p0: DialogInterface?) {
        viewBinder.backUpBtn.visibility = View.GONE
        viewBinder.vsOp.visibility = View.GONE
    }

    override fun onDismiss(p0: DialogInterface?) {
        viewBinder.backUpBtn.visibility = View.VISIBLE
        viewBinder.vsOp.visibility = View.VISIBLE
    }

    override fun onText(text: IMGText?) {
        viewBinder.mEditorImg.addStickerText(text)
    }

    interface EditorResultListener {
        fun onResult(mAlbumFile: AlbumFile)
    }

    override fun onBackPressedSupport(): Boolean {
        if (viewBinder.mEditorImg.isClipping()) {
            onCancelClipClick()

            return true
        }
//
//        pop()

        return false
    }

}